$(function() {

	var partnerId = $('#partnerId').val();
	
	$('#new-search').click(function() {
		$('#redirect-after-block').hide();
		$('#frm-hotel-search').submit();
	});

	$('#back-to-search-results').click(function() {
		$('#redirect-after-block').hide();
		$('.cols > .panel').fadeIn();
	});

	var proposeShowFun = function(e) {
		$('a.propose_show').unbind();
		$('div.search_results').show();
		$('div.search_results.s_opened').hide();
		var
			$this = $(this);
			p = $this.parents('div.search_results'),
			d = $this.data(),
			ajaxData = {item_index: d.index, user_id: d.userId, rate_id: d.rateId, markup: d.markup, partnerId: partnerId}
		;
		
		timer = window.setTimeout(function() {searchWaitRedirect(d.index);}, tm.Config.searchResultsTimeout);
		
		//if (p.next(0).hasClass('s_opened')) {
		if (p.next(0).hasClass('s_opened') && p.next(0).html() != '') {
			$('#popupOverlay').hide();
			$('#popupLoading').hide();
			$('#popupWindow').hide();
			p.find('a.propose_show').removeClass('popup');
			p.find('a.propose_show').removeClass('wait-screen');
			p.next(0).find('.propositions .service_choose .row .input a.tm-radiobutton').each(function() {
				if (!$(this).prev(0).is(':radio')) {
					$(this).remove();
				}
			});
			p.hide();
			p.next(0).show();
			searchResultsEvents();
			$('a.propose_show').click(proposeShowFun);
		} else {
			if (!$.browser.msie) {
				$(this).parents('.search_results').css({opacity: '0.5', position: 'relative'}).append('<div id="thisAjaxLoader" style="position:absolute; background:url(/i/ajax-loader-transparent.gif) 50% 50% no-repeat; width:100%; height:100px; margin:-110px 0 0 0;"></div>');
			} else if ($.browser.msie && $.browser.version.number > 6) {
				$(this).parents('.search_results').css({position: 'relative'}).append('<div id="thisAjaxLoader" style="position:absolute; background:url(/i/ajax-loader-transparent.gif) 50% 50% no-repeat; width:100%; height:100px; margin:-110px 0 0 0;"></div>');
			}
			
			$.get('/a_ajax/avail/hotel.search', ajaxData, function(data) {
				window.clearTimeout(timer);
				if (!$.browser.msie) {
					$('#thisAjaxLoader').parents('.search_results').css({opacity: '1', position: 'static'});
				} else if ($.browser.msie && $.browser.version.number > 6) {
					$('#thisAjaxLoader').parents('.search_results').css({position: 'static'});
				}
				$('#thisAjaxLoader').remove();
				if (data == 'error') {
					if(!location.href.match(/expandHotel=/i)) {
						location.href += '&expandHotel=' + d.index;
					}
					$('a.propose_show').click(proposeShowFun);
					return;
				}
				var newData = $(data);
				p.hide();
				p.next(0).prepend(newData);
				
				if (!$.browser.msie) {
					p.next(0).show();
				} else {
					setTimeout(function() {
						p.next(0).show();
					}, 1);
				}
				p.find('a.propose_show').removeClass('popup');
				p.find('a.propose_show').removeClass('wait-screen');
				if (!p.next(0).find('.search_results_item .photo a img').hasClass('default')) {
					var
						thisIMG = p.next(0).find('.search_results_item .photo a img'),
						thisSRC = thisIMG.attr('src'),
						thisWIDTH = thisIMG.attr('width'),
						thisHEIGHT = thisIMG.attr('height'),
						thisALT = thisIMG.attr('alt')
					;
					p.find('.search_results_item .photo a img').removeClass('default').attr({
						src: thisSRC,
						width: thisWIDTH,
						height: thisHEIGHT,
						alt: thisALT
					});
				}

				setTimeout(function() {
					p.next(0).find('a.propose_hide').click(function() {
						var s = $(this).parents('div.search_results.s_opened');
						s.prev().show();
						s.hide();
					});
					searchResultsEvents();
					orderEvent();
				}, 1);
				
				
				$('a.propose_show').click(proposeShowFun);
			});
		}
	};
	$('a.propose_show').click(proposeShowFun);
	
	var orderEvent = function() {
		var exportType = $('#exportType').val();
		var order_button_fn;
		order_button_fn = order_button_click;
		if ($('#exportType').length > 0 && exportType != '') {
			if (exportType == 'REDIRECT') {
				order_button_fn = order_button_click_tm_open;
			} else if (exportType == 'MAIL') {
				order_button_fn = order_button_click;
			}
		}
		
		$('.s_opened').not(':hidden').find('.order-button').bind('click', order_button_fn);
		
		function order_button_click() {
			$('.user-message').hide();
			var $this = $(this);
			var hotelName = $(this).parents('.s_opened').find('.search_results_item .item_desc h3 a').text();
			$('#user_hotel').val(hotelName);
			$('#text_user_hotel').text(hotelName);
			var hidePanel = $(this).parents('.cols').children('.panel');
			hidePanel.hide();
			$('#dataForm').show();
			$('#user_name').focus();
			$('#dataFormCancel').click(function() {
				$('#dataForm').hide();
				hidePanel.show();
				$('#dataFormSubmit').unbind('click', dataFormSubmitFunc);
				return false;
			});
			$('#dataFormSubmit').bind('click', dataFormSubmitFunc);
			function dataFormSubmitFunc() {
				var user_name_val = $.trim($('#user_name').val());
				var user_phone_val = $.trim($('#user_phone').val());
				
				if (user_name_val != '' && user_phone_val != '') {
					
					$('#dataFormPartnerId').val($('#partnerId').val());
					// Codes
					$('#dataFormHotelCode').val($this.parents('form.propositions').prev('.search_results_item').find('.item_desc .subdesc .hotel_code .body').text().replace(/[\s\t\r\n]+/, ''));
					
					$('#frm-dataForm input[name="room[]"]').remove();
					$this.parents('form.propositions').find('.d_propositions .room_choose input[type="radio"]:checked').each(function() {
						var inp = $('<input type="hidden" name="room[]" />');
						inp.val($(this).parents('.row-2').find('.desc .room_type .code').text().replace(/[\s\t\r\n]+/, ''));
						inp.appendTo('#frm-dataForm');
					});
					
					$('#dataFormTransferCode').val($this.parents('form.propositions').find('.d_propositions .transfer_choose .row.selected .desc .code').text().replace(/[\s\t\r\n]+/, ''));
					// Form info
					$('#dataFormCountry').val($.trim($('#selector-country option:selected').val()));
					$('#dataFormCity').val($.trim($('#selector-city option:selected').val()));
					$('#dataFormDateFrom').val($('#depdate').val());
					$('#dataFormDateTo').val($('#enddate').val());
					
					var ages = [];
					$('#adults-list li:visible select').each(function() {
						ages.push($(this).val());
					});

					var starsArray = [];
					for (var i = 1; i <=5; i++) {
						var ch = $('#h_class_' + i);
						if (ch.attr('checked')) {
							starsArray.push(i);
						}
					}
					$('#dataFormStars').val(starsArray.join(','));
					
					$('#dataFormRoomsCount').val($('#rooms').val());
					$('#dataFormPriseFrom').val($('#price-from').val());
					$('#dataFormPriseTo').val($('#price-to').val());
					$('#dataFormBoardType').val($('#nutrition-type option:selected').val());
					
					$('#searchURL').val(location.href);
					
					
					function ajaxSendDataSuccess(data) {
						if (data == 'success') {
							$('#dataForm').hide();
							hidePanel.show();
							$('.ajaxSendDataSuccess').show();
							$('body').scrollTo(0, 0, {queue:true});
						} else {
							$('.ajaxSendDataError').show();
							$('#dataForm').hide();
							hidePanel.show();
							$('#dataFormSubmit').unbind('click', dataFormSubmitFunc);
						}
						$('#dataFormSubmit').unbind('click', dataFormSubmitFunc);
					}
					function ajaxSendDataError() {
						$('.ajaxSendDataError').show();
						$('#dataForm').hide();
						hidePanel.show();
						$('#dataFormSubmit').unbind('click', dataFormSubmitFunc);
					}
					$('#frm-dataForm').ajaxSubmit({
						url: '/a_search/hotelexport.order',
						data: {'passengerAges[]': ages},
						success: ajaxSendDataSuccess,
						error: ajaxSendDataError
					});
				} else {
					alert('Пожалуйста заполните поля, отмеченные (*)');
				}
				return false;
				
			};
		}
		
		function order_button_click_tm_open() {
			$(this).parents('form').attr({action: '/a_cart/hotel.add', target: '_blank'}).submit(function() {});
			$(this).parents('.cols').children('.panel').hide();
			$('#redirect-after-block').show();
		}
	};
	
	
	var searchResultsEvents = function() {
		$('.transfers-block-show a').click(function() {
			$(this).parents('.transfers-block-show').siblings('.transfers-block').show();
			$(this).parents('.transfers-block-show').hide();
		});
		$('.transfers-block-hide a').click(function() {
			$(this).parents('.transfers-block').siblings('.transfers-block-show').show();
			$(this).parents('.transfers-block').hide();
		});

		$('.propositions .d_propositions div.service_choose div.row').mouseover(function() {
			var $this = $(this);
			if (!$this.hasClass('selected')) {
				$this.addClass('hovered');
			}
		});
		
		var isSynchronize = false;
		var isSynchronizeCode = false;
		if ($('form.propositions input[name="avail_sync"]').length > 0) {
			isSynchronize = true;
		}
		if ($('form.propositions input[name="avail_sync_code"]').length > 0) {
			isSynchronizeCode = true;
		}

		
		$('div.service_choose div.row').mouseout(function() {
			$(this).removeClass('hovered');
		}).mousedown(function() {
			var $this = $(this);
			if (isSynchronize) {
				var index = parseInt($this.find('input[type="radio"]').val()) + 1;
				var $that = $this.parents('div.d_propositions').find('div.service_choose').find('div.row:nth-child(' + index + ')');
				$that.parents('.service_choose').find('div.selected').removeClass('selected');
				$that.parents('.service_choose').find('a.tm-radiobutton img').removeClass('checked');
				$that.find('input[type="radio"]').trigger('click').next(0).find('img').addClass('checked');
				$that.addClass('selected').removeClass('hovered');
			} else if (isSynchronizeCode) {
				var parent = $this.parents('div.d_propositions');
				var rooms = parent.find('div.room_choose').size();
				var sc = parent.find('div.service_choose');
				var rowsRoomCodes = [];
				var roomServices = [];
				parent.find('div.room_choose').each(function() {
					roomServices.push($(this));
				});
				for (var i = 1; i <= rooms; i++) {
					rowsRoomCodes[i-1] = roomServices[i-1].find('div.row:first-child input.room-code').val();
				}
				var code = $this.find('input.room-code').val();
				var neededRow = parent.find('div.service_choose .row').filter(function() {
					if ($(this).find('input.room-code').val() == code) return $(this);
				});
				neededRow.siblings('.row').removeClass('selected');
				neededRow.addClass('selected').removeClass('hovered');
				neededRow.siblings('.row').find('div.input input').next(0).find('img').removeClass('checked');
				neededRow.find('div.input input').trigger('click').next(0).find('img').addClass('checked');
			} else {
				$this.parents('.service_choose').find('div.selected').removeClass('selected');
				$this.parents('.service_choose').find('a.tm-radiobutton img').removeClass('checked');
				$this.find('input[type="radio"]').trigger('click').next(0).find('img').addClass('checked');
				$this.addClass('selected').removeClass('hovered');
			}
			recalculatePrice(this);
		});
		
		var recalculatePrice = function(elm) {
			var cashType, transferPrice, summary, summaryPrice, roomPrice = [], roomPriceAll = 0, cashAfter = false;
			
			summary = $(elm).parents('form.propositions').find('.search_result_bottom .summary .summ');
			
			$(elm).parents('form.propositions').find('.room_choose').each(function() {
				var
					$this = $(this),
					prc = $this.find('.row.selected .price').length > 0 ? $.trim($this.find('.row.selected .price strong').text()) : '0'
				;
				roomPrice.push(prc);
			});
			
			if ($(elm).parents('form.propositions').find('.transfer_choose').length > 0) {
				transferPrice = $(elm).parents('form.propositions').find('.transfer_choose .selected .price').html().replace(/(^\s+)|(\s+$)/gi, '');
			} else {
				transferPrice = '';
			}

			/*for (var j = 0; j < roomPrice.length; j++) {
				if (roomPrice[j].length > 1 && roomPrice[j] != null) {
					cashType = roomPrice[j].match(/(^\S)/gi);
					break;
				} else if (transferPrice.length > 1 && transferPrice != null) {
					cashType = transferPrice.match(/(^\S)/gi);
					break;
				} else {
					cashType = '';
					break;
				}
			}*/

			if (roomPrice[0].length > 0 && roomPrice[0] != null) {
				cashType = roomPrice[0].replace(/[0-9]+/gi, '');
				if (isNaN(parseInt(roomPrice[0].substr(0,1))))
					cashAfter = false;
				else
					cashAfter = true;
			} else
				cashType = '';

			for (var i = 0; i < roomPrice.length; i++) {
				roomPrice[i] = (roomPrice[i].length > 1 && roomPrice[i] != null) ? roomPrice[i].match(/[0-9]+/gi, '') : '0';
				roomPriceAll += parseInt(roomPrice[i]);
			}
			transferPrice = (transferPrice.length > 1 && transferPrice != null) ? transferPrice.replace(/(^\S)/gi, '') : '0' ;

			summaryPrice = roomPriceAll + parseInt(transferPrice);
			var resultText = '';
			if (cashAfter) {
				resultText = summaryPrice + '' + cashType;
			} else {
				resultText = cashType + '' + summaryPrice;
			}
			summary.text(resultText);
		};
		
	};
	
	var expandHotelElem = $('a.propose_show').filter(function(i){
		var v = $(this).data().expandHotel;
		return (v != undefined && v.length > 0);
	}).eq(0);
	if(expandHotelElem.size() == 1)
	{
		expandHotelElem.trigger('click');
	}
	
	if ($('div.search_results').length > 0) {
		var hIndexes = [];
		var hImages = [];
		var hCC = [];
		var hDC = [];
		
		$('.search_results .search_results_item .photo a img.default').each(function() {
			hIndexesIndex = $(this);
			hIndexes.push(hIndexesIndex.parents('a').data().index);
			hCC.push(hIndexesIndex.parents('a').data().cc);
			hDC.push(hIndexesIndex.parents('a').data().dc);
			hImages.push(hIndexesIndex);
		});
		var i = 0;
		var numOfIndexes = hIndexes.length;
		
		if (numOfIndexes > 0) {
			ajaxReq(hIndexes, hCC, hDC, hImages, i, numOfIndexes);
		}
	}
	
	function ajaxReq(codes, hCC, hDC, images, i, numOfIndexes) {
		if($('#iLoadHotelsContent').val() == 0) {
			return;
		}
		$.ajax({
			url: '/a_ajax/content/hotel',
			data: {hc: codes[i], cc: hCC[i], dc: hDC[i]},
			dataType : "json",
			type: 'GET',
			
			beforeSend: function() {
				images[i].after('<img class="ajax-loader" src="/i/ajax-loader-transparent.gif" width="35" height="35" alt="" />');
			},
			success: function(res){
					// error = 0 - not errors;
					// error = 1 - empty hotel code or country code
					// error = 2 - if content hotel exist or vendor - S2S
					// error = 3 - empty content hotel
					// error = 4 - content not saved
					// error = 5 - exception
					// error = 6 - empty image src
				if (res.error == 0 && res.src != '') {
					images[i].removeClass('default').attr({
						src: res.src,
						width: res.width,
						height: res.height
					});
					images[i].next('img.ajax-loader').remove();
				}
				if (res.error != 0) {
					images[i].removeClass('default');
					images[i].next('img.ajax-loader').remove();
				}
				if (i < numOfIndexes - 1) {
					i++;
					ajaxReq(codes, hCC, hDC, images, i, numOfIndexes);
				} else {
					return;
				}
  			},
			error: function() {
				if (images[i+1] != undefined) {
					i++;
					ajaxReq(codes, hCC, hDC, images, i, numOfIndexes);
				}
				images[i].removeClass('default');
				images[i].next('img.ajax-loader').remove();
			}
		});
	}
	
	function searchWaitRedirect(e) {
		if (!location.href.match(/expandHotel/)) {
			var domain = location.href + '&expandHotel=' + e;
			location.href = domain;
		}
	}

});

var newwindow;
function pop(url) {
	newwindow=window.open(url,'name','height=768,width=1024, resizable=0,menubar=0,toolbar=0,location=0,status=0,statusbar=0,scrollbars=1');
	if (window.focus) {
		newwindow.focus();
	}
}
